<?php

namespace app\controller\teacher;

use app\BaseController;
use app\model\Exam;
use app\model\Course;
use app\model\Question;
use app\model\VStudentCourse;
use app\model\StudentExam;
use \think\facade\Db;

/**
 * 教师-测验控制器
 */
class TeacherExam extends BaseController
{

    /**
     * 测验列表
     */
    public function list()
    {

        $examList = Exam::field(['EID', 'courseID', 'title', 'type', 'startTime', 'endTime', 'credit'])
            ->where(['TID' => $this->user['TID'], 'courseID' => $this->request->param("courseID")])
            ->select();
        return resultSuccess($examList);
    }

    /**
     * 获取单个测验
     */
    public function getExam()
    {
        $exam = Exam::field(['EID', 'courseID', 'title', 'type', 'startTime', 'endTime', 'credit', 'questions'])
            ->where(['TID' => $this->user['TID'], 'EID' => $this->request->param('EID')])
            ->find();
        if ($exam == null) {
            return resultError('无权限');
        }
        return resultSuccess($exam);
    }

    /**
     * 添加测验
     */
    public function add()
    {
        $data = $this->request->param();
        $data['EID'] = null;
        $data['TID'] = $this->user['TID'];
        if ($data['startTime'] > $data['endTime']) {
            return resultError('时间错误');
        }
        $data['startTime'] = date('Y-m-d H:i:s', $data['startTime'] / 1000);
        $data['endTime'] = date('Y-m-d H:i:s', $data['endTime'] / 1000);
        $data['status'] = 0;
        $exam = new Exam($data);
        if ($exam->save()) {
            return resultSuccess();
        } else {
            return resultError();
        }
    }

    /**
     * 删除测验
     */
    public function delete()
    {
        $EID = $this->request->param('EID');
        $exam  = Exam::where('TID', $this->user['TID'])->find($EID);
        if (empty($exam)) {
            return resultError();
        }
        if ($exam->delete()) {
            return resultSuccess();
        } else {
            return resultError();
        }
    }

    /**
     * 修改测验信息
     */
    public function edit()
    {
        $data =  $this->request->param();
        $exam  = Exam::where('TID', $this->user['TID'])->find($data['EID']);
        if (empty($exam)) {
            return resultError();
        }
        $exam->title = $data['title'];
        $exam->type = $data['type'];
        $exam->questions = $data['questions'];
        $exam->startTime = date('Y-m-d H:i:s', $data['startTime'] / 1000);
        $exam->endTime = date('Y-m-d H:i:s', $data['endTime'] / 1000);
        if ($exam->save()) {
            return resultSuccess();
        } else {
            return resultError();
        }
    }

    /** 
     * 获取多个学生测试简介
     */
    public function listStudentExam()
    {
        $EID = $this->request->param("EID");
        $TID = $this->user['TID'];
        $exam = Exam::where(["TID" => $TID, "EID" => $EID])->find();
        if (empty($exam)) {
            return resultError();
        }
        //此处判断该教师是否有权限
        //$studentExam = StudentExam::field(['studentexam.SID'=>'SID', 'credit', 'studentName'])->where(["EID" => $exam['EID']])->rightjoin('v_studentcourse', 'v_studentcourse.SID = studentexam.SID')->select();
        $studentList = VStudentCourse::field(['v_studentcourse.SID' => 'SID', 'studentName', 'claseName', 'credit'])->where('courseID', $exam->courseID)->leftjoin('studentexam', 'v_studentcourse.SID = studentexam.SID and EID =' . $exam->EID)->select();
        return resultSuccess($studentList);
    }

    /**
     * 获取单个学生测试详情
     */
    public function getStudentExam()
    {
        $EID = $this->request->param("EID");
        $SID = $this->request->param("SID");
        $TID = $this->user['TID'];
        $exam = Exam::where(["TID" => $TID, "EID" => $EID])->find();
        if (empty($exam)) {
            return resultError();
        }
        //此处判断该教师是否有权限
        $QIDList = array_column((array)$exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, (array)$exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::select($QIDList)->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $key => $question) {
            $questionList[$key]['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $totalScore += $questionList[$key]['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $QIDList = array_column((array)$exam['questions'], 'QID');
        sort($QIDList);
        $questionList = array_combine((array)$QIDList, (array)$questionList);
        $studentExam = StudentExam::where(["EID" => $exam['EID'], 'SID' => $SID])->find();
        //为问题数组添加索引
        return resultSuccess([
            'studentExam' => $studentExam,
            'questionList' => $questionList
        ]);
    }

    /**
     * 获得题目统计
     */
    public function getQuestionCount()
    {
        $EID = $this->request->param("EID");
        $SID = $this->request->param("SID");
        $TID = $this->user['TID'];
        $exam = Exam::where(["TID" => $TID, "EID" => $EID])->find();
        if (empty($exam)) {
            return resultError();
        }
        //此处判断该教师是否有权限
        $QIDList = array_column((array)$exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, (array)$exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::select($QIDList)->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $key => $question) {
            $questionList[$key]['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $questionList[$key]['answer'] = (array)$questionList[$key]['answer'];
            $totalScore += $questionList[$key]['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $QIDList = array_column((array)$exam['questions'], 'QID');
        sort($QIDList);
        $questionList = array_combine((array)$QIDList, (array)$questionList);
        //题目获取段
        $studentExams = StudentExam::field(['correction', 'answer'])->where(["EID" => $exam['EID']])->select()->toArray();
        //获取学生测验批改后列表
        foreach ($studentExams as $studentExam) {
            if ($studentExam['correction']) {
                foreach ($studentExam['correction']->detail as $key => $correction) {
                    if($questionList[(string)$correction['QID']]['type'] == 4) continue;
                    //如果非选择题，跳过
                    if(empty($questionList[(string)$correction['QID']]['count'])){
                        $questionList[(string)$correction['QID']]['count'] = [];
                    }
                    //判断该题是否为空
                    if($questionList[(string)$correction['QID']]['type'] == 0){
                        if (empty($questionList[(string)$correction['QID']]['count'][(string)$studentExam['answer']->$key['QID']])) {
                            $questionList[(string)$correction['QID']]['count'][(string)$studentExam['answer']->$key['answer']] = 1;
                        } else {
                            $questionList[(string)$correction['QID']]['count'][(string)$studentExam['answer']->$key['answer']] += 1;
                        }
                    }
                    //单选
                    else if($questionList[(string)$correction['QID']]['type'] == 1){
                        foreach($studentExam['answer']->$key['answer'] as $answer){
                            if (empty($questionList[(string)$correction['QID']]['count'][(string)$studentExam['answer']->$key['QID']])) {
                                $questionList[(string)$correction['QID']]['count'][(string)$answer] = 1;
                            } else {
                                $questionList[(string)$correction['QID']]['count'][(string)$answer] += 1;
                            }
                        } 
                    }
                    //多选
                    else{
                        if (empty($questionList[(string)$correction['QID']]['count'][(string)$studentExam['answer']->$key['QID']])) {
                            if($correction['isCorrect'] == true)
                            $questionList[(string)$correction['QID']]['count']['true'] = 1;
                            else
                            $questionList[(string)$correction['QID']]['count']['false'] = 1;
                        } else {
                            if($correction['isCorrect'] == true)
                            $questionList[(string)$correction['QID']]['count']['true'] += 1;
                            else
                            $questionList[(string)$correction['QID']]['count']['false'] += 1;
                        }
                    }
                    //判断或者填空题
                    //主观题无需统计
                }
            }
        }
        //为问题数组添加索引
        return resultSuccess([
            //'studentExams' => $studentExams,
            'questionList' => $questionList
        ]);
    }

    /**
     * 自动批卷
     */
    public function correctExam()
    {

        $EID = $this->request->param("EID");
        $TID = $this->user['TID'];
        $exam = Exam::where(["TID" => $TID, "EID", $EID])->find();
        if (empty($exam)) {
            return resultError();
        }

        $QIDList = array_column($exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, $exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::where("QID", $QIDList)->select()->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $question) {
            $question['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $totalScore += $question['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $QIDList = array_column($exam['questions'], 'QID');
        $questionList = array_combine($QIDList, $questionList);
        //为问题数组添加索引
        $studentExamList = StudentExam::where("EID", $exam['EID'])->select()->toArray();
        //获取学生作答信息列表

        foreach ($studentExamList as $studentExam) {
            $studentAnswerList = $studentExam['answer'];
            $correction = [
                'totalScore' => 0
            ];
            foreach ($studentAnswerList as $studentAnswer) {
                $QID = $studentAnswer['QID'];
                if (isset($questionList[$QID])) {
                    //是否存在该问题
                    if ($questionList[$QID]['answer'] != $studentAnswer['answer']) {
                        $correction['totalScore'] += $questionList[$QID]['score'];
                        //添加总分
                        $correction['detail'] = [
                            'QID' => $QID,
                            'isCorrect' => true,
                            'score' => $questionList[$QID]['score']
                        ];
                    } else {
                        $correction['detail'] = [
                            'QID' => $QID,
                            'isCorrect' => false,
                            'score' => 0
                        ];
                    }
                }
                //判断题目是否正确并存入判题数组
            }
            $credit = $exam['credit'] * floor($correction['totalScore'] / $totalScore);
            $save = StudentExam::update(
                ['correction' => $correction, 'credit' => $credit],
                ['SID' => $studentExam['SID'], 'EID' => $EID]
            );
            //保存当前学生-测验数据
            if ($save == false) {
                return resultError();
            }
        }
        return resultSuccess();
    }

    /**
     * 单独学生改卷
     */
    public function correctSingalExam()
    {
        $EID = $this->request->param("EID");
        $SID = $this->request->param("SID");
        $TID = $this->user['TID'];
        $exam = Exam::where(["TID" => $TID, "EID" => $EID])->find();
        if (empty($exam)) {
            return resultError();
        }
        //此处判断该教师是否有权限
        $QIDList = array_column((array)$exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, (array)$exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::select($QIDList)->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $key => $question) {
            $questionList[$key]['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $totalScore += $questionList[$key]['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $correctionPre = $this->request->param('correction');
        $correction = ['detail' => $correctionPre, 'totalScore' => 0];
        foreach ($correctionPre as $cp) {
            $correction['totalScore'] += $cp['score'];
        }
        $credit = $exam['credit'] * floor($correction['totalScore'] / $totalScore);
        $save = StudentExam::update(
            ['correction' => $correction, 'credit' => $credit],
            ['SID' => $SID, 'EID' => $EID]
        );
        //保存当前学生-测验数据
        if ($save == false) {
            return resultError();
        }
        return resultSuccess();
    }
}
